package common;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Vector;

public class SkillManSearch 
{
	private String cwd;
	private SkillManInstance base;
	private File[] instFiles;
	private Vector<SkillManInstance> onts;
	private SkillManSchema schema;
	private Vector<MySearchElement> results;
	
	public SkillManSearch( SkillManSchema instSchema, SkillManInstance baseInst, String instDir )
	{
		if( !instDir.equals("") && instDir.charAt( instDir.length()-1 )!='/' )
			instDir+="/";
		
		cwd=instDir;
		base=baseInst;
		schema=instSchema;
		onts=new Vector<SkillManInstance>();
	}
	
	public void loadFiles()
	{
		File dir=new File(cwd+".");
		instFiles=dir.listFiles();
		
		System.out.println("Loaded instances: ");
		for( int i=0; i<instFiles.length; i++ )
		{
			System.out.println((i+1)+". "+instFiles[i].getName());
		}
	}
	
	public void loadOnts() throws FileNotFoundException
	{
		System.out.println("Creating SkillManInstance s from files:");
		for( int i=0; i<instFiles.length; i++ )
		{
			SkillManInstance inst=new SkillManInstance(schema, instFiles[i].getAbsolutePath());
			inst.load();
			System.out.println("Loaded: "+inst.getProperyValue(SkillManInstance.foafNS+"Person", SkillManInstance.foafNS+"name"));
			onts.add(inst);
		}
	}
	
	public void compareToAll()
	{
		results=new Vector<MySearchElement>();
		
		for( int i=0; i<onts.size(); i++ )
		{
			SkillManInstance inst=onts.get(i);
			float affinity=inst.compareTo(base);
			System.out.println("Base and instance "+(i+1)+" affinity: "+affinity+"%");
			MySearchElement e=new MySearchElement();
			e.inst=inst;
			e.affinity=affinity;
			results.add(e);
		}
	}
	
	public void sortResults()
	{
		java.util.Collections.sort(results, Collections.reverseOrder());
		System.out.println("Sorted results: ");
		for( int i=0; i<results.size(); i++ )
		{
			System.out.println((i+1)+".");
			System.out.println("\t"+results.get(i).inst.getProperyValue(SkillManInstance.foafNS+"Person", SkillManInstance.foafNS+"name"));
			System.out.println("\tAffinity: "+results.get(i).affinity);
		}
	}
	
	public String sortResultsList()
	{
		java.util.Collections.sort(results, Collections.reverseOrder());
		String output="Sorted results: <table><tr>";
		
		for( int i=0; i<results.size(); i++ )
		{
			output+="<td> "+(i+1)+". </td>";
			output+="<td> "+results.get(i).inst.getProperyValue(SkillManInstance.foafNS+"Person", SkillManInstance.foafNS+"name")+" </td>";
			output+="</tr><tr><td/><td> Affinity: "+results.get(i).affinity+" </td></tr>";
		}
		return output+"</table>";
	}
	
	public Vector<MySearchElement> getResults()
	{
		return results;
	}
}
